package com.web.config;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.apache.ibatis.session.Configuration;
import org.springframework.stereotype.Component;

import com.mysql.cj.jdbc.MysqlDataSource;

//@configuration == @component
@Component
@MapperScan("com.web.dao")
public class MyBatisConfig {

	@Bean
	public MysqlDataSource mysqlDataSource() {
		//
		MysqlDataSource dataSource = new MysqlDataSource();
		// 设置mysql数据源属性
		dataSource.setServerName("localhost");
		dataSource.setPortNumber(3306);
		dataSource.setDatabaseName("wisdom");
		dataSource.setUser("root");
		dataSource.setPassword("123456");
		return dataSource;
	}

//初始化mybatis环境，使用Java类的配置方法
	@Bean
	public SqlSessionFactory sqlSessionFactory(MysqlDataSource mysqlDataSource) {
		// 加载事物的模块
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		// 加载mybatis环境，development 表示当前mybatis的环境是开发者专用
		Environment environment = new Environment("development", transactionFactory, mysqlDataSource);
		// 生成对应的配置类
		Configuration configuration = new Configuration(environment);
		// 额外配置：数据库下划线字段，自动映射javabean的驼峰命名法规则
		configuration.setMapUnderscoreToCamelCase(true);
		// SqlSessionFactroy对象，该对象是jdbc的Connection的创建工厂
		SqlSessionFactory sqlSessionFactory = new  SqlSessionFactoryBuilder().build(configuration);
		return sqlSessionFactory;
	}
	
}
